<template>
  <div class="table-page-search-wrapper commonSelectWidth listSearchWrap" id="taskListSearchWrap">
    <a-form class="newEditStyle" style="display: flex">
      <a-row :gutter="10" style="flex: 1 0 0">
        <!-- 状态 -->
        <a-col :md="24" :lg="4">
          <a-form-item :colon="false">
            <a-select
              mode="multiple"
              :maxTagCount="1"
              allow-clear
              v-model="queryParams.status"
              @change="$emit('change', queryParams)"
              :placeholder="$t('pleaseSelect') + $t('campaignStatus').toLowerCase()"
            >
              <a-select-option v-for="(item, index) in taskStatusSelect" :key="index" :value="item.value">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="24" :lg="4">
          <a-form-item :colon="false">
            <a-input
              v-model.trim="queryParams.name"
              @change="$emit('change', queryParams)"
              :placeholder="$t('pleaseInput') + $t('campaignName').toLowerCase()"
              @keyup.enter="doAction('refreshData')"
              allowClear
            />
          </a-form-item>
        </a-col>
        <a-col :md="24" :lg="8">
          <filter-box-collection
            :queryParam="queryParamsDesc"
            @removetag="removeQueryKey"
            @search="doAction('refreshData')"
            ref="taskListSearchFilterBox"
          >
            <template slot>
              <a-row :gutter="48" ref="taskListSearchFilterBoxRow" style="position: relative">
                <a-col :sm="24">
                  <a-form-item :label="$t('vehicleModel')" :colon="false">
                    <car-model-select
                      :query="{ }"
                      :default-value="queryParams.modelId"
                      :placeholder="$t('pleaseSelect')+$t('vehicleModel')"
                      :hasAll="false"
                      :clear="true"
                      mode="default"
                      @changeoption="(val) => {queryParams.modelId = val;$emit('change', queryParams)}"
                      style="width: 100%"
                    ></car-model-select>
                  </a-form-item>
                </a-col>
                <!-- 车辆版本 -->
                <a-col :sm="24">
                  <a-form-item :label="$t('smartDrivingDomainVersion')" :colon="false">
                    <vehicle-version-name-select
                      ref="vehicleVersionRef"
                      mode="default"
                      :time="time"
                      :default-value="selectedVehicleVersion"
                      @changeoption="(val) => {queryParams.vehicleVersion = val;$emit('change', queryParams)}"
                    ></vehicle-version-name-select>
                  </a-form-item>
<!--                  @changeoption="handleSelectOption('vehicleVersionRef', 'vehicleVersion', $event, '', 'options')"-->
                </a-col>
                <!-- 升级类型 -->
                <a-col :sm="24">
                  <a-form-item :label="$t('upgradeType')" :colon="false">
                    <task-upgrade-type
                      ref="taskTypeSelectRef"
                      :default-value="taskType"
                      @changeoption="handleSelectOption('taskTypeSelectRef', 'type', $event, 'value', 'taskType')"
                    ></task-upgrade-type>
                  </a-form-item>
                </a-col>
                <!-- 升级策略 -->
                <a-col :sm="24">
                  <a-form-item :label="$t('sjcl')" :colon="false">
                    <update-strategy-select
                      :type="1"
                      ref="strategyRef"
                      :time="time"
                      :version-type="'uat'"
                      :default-strate-id="selectedStrategyId"
                      :readonly="!upgradeTriggerType"
                      :getPopupContainer="getPopupContainer"
                      @changeoption="handleSelectOption('strategyRef', 'strategyId', $event, 'id', 'strategyOptions')"
                    ></update-strategy-select>
                  </a-form-item>
                </a-col>
                <!-- 是否静默升级 -->
                <a-col :sm="24">
                  <a-form-item :label="$t('sfjmsj')" :colon="false">
                    <task-silence-type
                      ref="TaskSilenceTypeRef"
                      :default-value="silenceUpgrade"
                      @changeoption="
                        handleSelectOption('TaskSilenceTypeRef', 'silenceUpgrade', $event, 'id', 'slienceUpgradeType')
                      "
                    >
                    </task-silence-type>
                  </a-form-item>
                </a-col>
                <!-- 是否强制升级 -->
                <a-col :sm="24">
                  <a-form-item :label="$t('isQzsj')" :colon="false">
                    <task-force-type
                      ref="TaskForceTypeRef"
                      :default-value="forceUpgrade"
                      @changeoption="
                        handleSelectOption('TaskForceTypeRef', 'forceUpgrade', $event, 'id', 'forceUpgradeType')
                      "
                    >
                    </task-force-type>
                  </a-form-item>
                </a-col>

                <!-- 活跃度 -->
                <a-col :sm="24">
                  <a-form-item :label="$t('activityLevel')" :colon="false">
                    <activity-level-select
                      ref="activityLevelSelectRef"
                      :default-value="activityLevel"
                      @changeoption="handleSelectOption('activityLevelSelectRef', 'lastActive', $event)"
                    ></activity-level-select>
                  </a-form-item>
                </a-col>
                <!-- 最近升级 -->
                <a-col :sm="24">
                  <a-form-item :label="$t('lastUpgrade')" :colon="false">
                    <last-upgrade-ok-select
                      ref="lastUpgradeOkSelectRef"
                      :default-value="lastUpgradeSuccess"
                      @changeoption="handleSelectOption('lastUpgradeOkSelectRef', 'lastUpgradeSuccess', $event)"
                    ></last-upgrade-ok-select>
                  </a-form-item>
                </a-col>
                <!-- 启用时间 -->
                <a-col :sm="24">
                  <a-form-item :label="$t('activationTime')" :colon="false">
                    <a-form-item :style="{ display: 'inline-block', width: 'calc(50% - 12px)', marginBottom: 0 }">
                      <a-date-picker
                        format="YYYY-MM-DD"
                        :disabledDate="disabledEffStartDate"
                        style="width: 100%"
                        v-model="queryParams.enableTimeGte"
                        :getCalendarContainer="getDatePickerContainer"
                        @openChange="openDateChange"
                        @change="$emit('change', queryParams)"
                      />
                    </a-form-item>
                    <span :style="{ display: 'inline-block', width: '24px', textAlign: 'center' }">-</span>
                    <a-form-item :style="{ display: 'inline-block', width: 'calc(50% - 12px)', marginBottom: 0 }">
                      <a-date-picker
                        format="YYYY-MM-DD"
                        :disabledDate="disabledEffEndDate"
                        style="width: 100%"
                        v-model="queryParams.enableTimeLte"
                        :getCalendarContainer="getDatePickerContainer"
                        @openChange="openDateChange"
                        @change="$emit('change', queryParams)"
                      />
                    </a-form-item>
                  </a-form-item>
                </a-col>
                <!-- 创建时间 -->
                <a-col :sm="24">
                  <a-form-item :label="$t('dateOfCreation')" :colon="false">
                    <a-form-item :style="{ display: 'inline-block', width: 'calc(50% - 12px)', marginBottom: 0 }">
                      <a-date-picker
                        format="YYYY-MM-DD"
                        :disabledDate="disabledCreStartDate"
                        style="width: 100%"
                        v-model="queryParams.createTimeGte"
                        :getCalendarContainer="getDatePickerContainer"
                        @openChange="openDateChange"
                        @change="$emit('change', queryParams)"
                      />
                    </a-form-item>
                    <span :style="{ display: 'inline-block', width: '24px', textAlign: 'center' }">-</span>
                    <a-form-item :style="{ display: 'inline-block', width: 'calc(50% - 12px)', marginBottom: 0 }">
                      <a-date-picker
                        format="YYYY-MM-DD"
                        :disabledDate="disabledCreEndDate"
                        style="width: 100%"
                        v-model="queryParams.createTimeLte"
                        :getCalendarContainer="getDatePickerContainer"
                        @openChange="openDateChange"
                        @change="$emit('change', queryParams)"
                      />
                    </a-form-item>
                  </a-form-item>
                </a-col>
              </a-row>
            </template>
          </filter-box-collection>
        </a-col>
        <a-col :xl="8" :lg="24">
          <div class="searchBtns">
            <a-button-group>
              <auth-button type="primary" :auth="taskPerms.view" @click="doAction('refreshData')">
                <i class="iconfont icon-chazhao"></i>
                {{ $t('inquiry') }}
              </auth-button>
              <a-button @click="doAction('clearCondition')">
                <i class="iconfont icon-qingkong"></i>
                {{ $t('clear') }}
              </a-button>
            </a-button-group>
            <auth-button :auth="taskPerms[upgradeTriggerType.toLowerCase()].add" @click="doAction('newTaskClick')">
              <i class="iconfont icon-xinjian"></i>
              {{ $t('task') }}
            </auth-button>
          </div>
        </a-col>
      </a-row>
      <a-row style="width: 100px; float: right">
        <a-col>
          <a-form-item>
            <a-button @click="doAction('toggleMultiAction')">
              <span v-if="info.isMultiAction">{{ $t('cancel') }}</span>
              <span v-else>{{ $t('bulkOperations') }}</span>
            </a-button>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </div>
</template>
<script>
import FilterBoxCollection from '@/components/SelfComponents/FilterBoxCollection'
import ActivityLevelSelect from '@/views/components/ActivityLevelSelect'
import LastUpgradeOkSelect from '@/views/components/LastUpgradeOkSelect'
import TaskUpgradeType from '@/views/components/TaskUpgradeType'
import TaskSilenceType from '@/views/components/TaskSilenceType'
import TaskForceType from '@/views/components/TaskForceType'
import AuthButton from '@/components/AuthButton'
import { taskPerms } from '@/config/permission/index'
import { mapState } from 'vuex'
import moment from 'moment'
import VehicleVersionNameSelect from '@/views/components/VehicleVersionNameSelect'
import UpdateStrategySelect from '@/views/components/StrategySelect'
import CarModelSelect from '@/views/components/CarModelSelect'

export default {
  props: {
    info: {
      type: Object,
      default () {
        return {}
      }
    },
    upgradeTriggerType: {
      type: String,
      default: ''
    },
    value: {
      type: Object,
      default: () => {
        return  {}
      }
    }
  },
  components: {
    FilterBoxCollection,
    ActivityLevelSelect,
    LastUpgradeOkSelect,
    TaskUpgradeType,
    TaskSilenceType,
    TaskForceType,
    AuthButton,
    VehicleVersionNameSelect,
    UpdateStrategySelect,
    CarModelSelect
  },
  computed: {
    ...mapState({
      // queryParams: (state) => state.task.queryParams,
      taskUpdateDictCode: (state) => state.dict.taskUpdateDictCode
    }),
    taskStatusSelect () {
      const arry = []
      var arrList=arry.concat(this.taskUpdateDictCode)
      if(this.upgradeTriggerType=== 'USER'){
        return arrList
      }else{
        return arrList.filter(item=>item.name!='已取消并删包')
      }
    },
    projectId () {
      return this.queryParams.projectId ? this.queryParams.projectId : this.$store.getters.myActiveProjectId
    },
    // 升级策略
    selectedStrategyId () {
      return this.queryParams.strategyId === null ? '' : this.queryParams.strategyId
    },
    // 车辆版本
    selectedVehicleVersion () {
      return this.queryParams.vehicleVersion === null ? '' : this.queryParams.vehicleVersion
    },
    // 活跃度
    activityLevel () {
      return this.queryParams.lastActive === null ? '' : this.queryParams.lastActive
    },
    // 最近升级
    lastUpgradeSuccess () {
      return this.queryParams.lastUpgradeSuccess === null ? '' : this.queryParams.lastUpgradeSuccess
    },
    // 升级类型
    taskType () {
      return this.queryParams.type === null ? undefined : this.queryParams.type
    },
    // 是否静默升级
    silenceUpgrade () {
      return this.queryParams.silenceUpgrade === null ? '' : this.queryParams.silenceUpgrade
    },
    // 是否强制升级
    forceUpgrade () {
      return this.queryParams.forceUpgrade === null ? '' : this.queryParams.forceUpgrade
    },
    queryParams:{
      get() {
        return this.value;
      },
      set(val) {
        this.$emit('change', val);    // 触发
      }
    }
  },
  model: {
    prop: "value", //绑定的值，通过父组件传递
    event: "change" //自定义事件名
  },
  data () {
    return {
      taskPerms,
      selectObj: {
        brandId: {
          fetch: 'getBrandName',
          data: null
        },
        vehicleType: {
          fetch: 'getVehicleTypeName',
          data: null
        },
        modelId: {
          fetch: 'getModelName',
          data: null
        }
      },
      queryParamsDesc: {},
      downloading: false,
      partList: [],
      time: Date.now()
    }
  },
  watch: {
    'queryParams.enableTimeGte' () {
      const vm = this
      vm.timeDecs('enableTime', 'activationTime')
    },
    'queryParams.enableTimeLte' () {
      const vm = this
      vm.timeDecs('enableTime', 'activationTime')
    },
    'queryParams.createTimeGte' () {
      const vm = this
      vm.timeDecs('createTime', 'dateOfCreation')
    },
    'queryParams.createTimeLte' () {
      const vm = this
      vm.timeDecs('createTime', 'dateOfCreation')
    },
    'queryParams.vehicleVersion' (value) {
      this.queryParamsDesc.vehicleVersion = value
    }
  },
  methods: {
    getPopupContainer (triggerNode) {
      return triggerNode.parentNode
    },
    doAction (key, data) {
      if (this[key]) {
        this[key](data || null)
        return
      }
      this.$emit('clickbtn', { type: key, data })
    },
    disabledEffStartDate (startValue) {
      const endValue = this.queryParams.enableTimeLte
      if (!startValue || !endValue) {
        return
      }
      // eslint-disable-next-line consistent-return
      return startValue.valueOf() > endValue.valueOf()
    },
    disabledEffEndDate (endValue) {
      const startValue = this.queryParams.enableTimeGte
      if (!startValue || !endValue) {
        return
      }
      // eslint-disable-next-line consistent-return
      return startValue.valueOf() >= endValue.valueOf()
    },
    disabledCreStartDate (startValue) {
      const endValue = this.queryParams.createTimeLte
      if (!startValue || !endValue) {
        return moment(startValue).format('YYYY-MM-DD') > moment().format('YYYY-MM-DD') // 不能用HH:mm:ss 因为当前日期不能选 体验就不好
      }
      return (
        moment(startValue).format('YYYY-MM-DD') > moment().format('YYYY-MM-DD') ||
        startValue.valueOf() > endValue.valueOf()
      )
    },
    disabledCreEndDate (endValue) {
      const startValue = this.queryParams.createTimeGte
      if (!endValue || !startValue) {
        return moment(endValue).format('YYYY-MM-DD') > moment().format('YYYY-MM-DD')
      }
      return (
        startValue.valueOf() > endValue.valueOf() ||
        moment(endValue).format('YYYY-MM-DD') > moment().format('YYYY-MM-DD')
      )
    },
    // 时间组合显示
    timeDecs (key, langKey) {
      const vm = this
      const startTime = vm.queryParams[`${key}Gte`] ? moment(vm.queryParams[`${key}Gte`]).format('YYYY-MM-DD') : ''
      const endTime = vm.queryParams[`${key}Lte`] ? moment(vm.queryParams[`${key}Lte`]).format('YYYY-MM-DD') : ''
      if (!startTime && !endTime) {
        vm.queryParamsDesc[key] = ''
      } else {
        vm.queryParamsDesc[key] = `${this.$t(langKey)}${startTime}~${endTime}`
      }
    },
    // 处理选择下拉选项数据
    handleSelectOption (ref, key, val, itemKey = 'value', optionKey = 'options') {
      console.log(ref, key, val, itemKey, optionKey)
      this.queryParams[key] = val
      console.log(this.queryParamsDesc, val, this.queryParams, '===========')
      this.$emit('change', this.queryParams)
      if (!val) {
        this.queryParamsDesc[key] = ''
        return
      }
      if (!itemKey) {
        this.queryParamsDesc[key] = val
        return
      }
      const obj = this.$refs[ref][optionKey].find((item) => item[itemKey] === val);
      if (obj) {
        this.queryParamsDesc[[key]] = obj.name
      }
    },
    // 删除搜索框中已选择的条件
    removeQueryKey (key) {
      console.log(key)
      if (typeof this.queryParams[key] === 'undefined') {
        this['remove' + key + 'Query']()
      } else {
        this.queryParams[key] = null
        console.log(this.queryParams[key])
      }
    },
    // 清除日期查询条件
    removeenableTimeQuery () {
      this.queryParams.enableTimeGte = null
      this.queryParams.enableTimeLte = null
    },
    // 清除日期查询条件
    removecreateTimeQuery () {
      this.queryParams.createTimeGte = null
      this.queryParams.createTimeLte = null
    },
    // 设置日期选择所在浮层的容器
    getDatePickerContainer () {
      return this.$refs.taskListSearchFilterBoxRow.$el
    },
    openDateChange (status) {
      if (status) {
        return
      }
      this.$refs.taskListSearchFilterBox.changeVisible(true)
    }
  }
}
</script>
<style lang="less">
.taskListSearchBtns {
  margin-top: -5px;
}
</style>
